package com.davidk.survey.client.datasource;

import com.davidk.survey.client.env.EnvironmentVariables;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.OperationBinding;
import com.smartgwt.client.data.RestDataSource;
import com.smartgwt.client.data.fields.DataSourceBooleanField;
import com.smartgwt.client.data.fields.DataSourceDateField;
import com.smartgwt.client.data.fields.DataSourceIntegerField;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.types.DSDataFormat;
import com.smartgwt.client.types.DSOperationType;
import com.smartgwt.client.types.DSProtocol;

public class UserDataSource extends RestDataSource {

	public UserDataSource() {
		setDataFormat(DSDataFormat.JSON);
		// dataSource.setRecordXPath("/dataResponse");
		// dataSource.setDataURL("api/survey/list");
		// dataSource.setDataURL("testdata");

		OperationBinding fetch = new OperationBinding();
		fetch.setOperationType(DSOperationType.FETCH);
		fetch.setDataProtocol(DSProtocol.GETPARAMS);
		OperationBinding add = new OperationBinding();
		add.setOperationType(DSOperationType.ADD);
		add.setDataProtocol(DSProtocol.POSTMESSAGE);
		OperationBinding update = new OperationBinding();
		update.setOperationType(DSOperationType.UPDATE);
		update.setDataProtocol(DSProtocol.POSTMESSAGE);
		OperationBinding remove = new OperationBinding();
		remove.setOperationType(DSOperationType.REMOVE);
		remove.setDataProtocol(DSProtocol.POSTMESSAGE);
		setOperationBindings(fetch, add, update, remove);

		DataSourceIntegerField idField = new DataSourceIntegerField("id", "ID");
		idField.setPrimaryKey(true);
		idField.setCanEdit(false);

		DataSourceTextField name = new DataSourceTextField("name", "name");
		DataSourceTextField email = new DataSourceTextField("email", "email");
		DataSourceTextField role = new DataSourceTextField("role", "role");
		DataSourceBooleanField isActive = new DataSourceBooleanField("isActive", "isActive");
		DataSourceDateField joinDate = new DataSourceDateField("joinDate", "joinDate");
		setFetchDataURL(EnvironmentVariables.User);
		setDataURL(EnvironmentVariables.UserSave);

		setFields(idField, name, email, role, isActive, joinDate);
	}

	@Override
	protected void transformResponse(DSResponse response, DSRequest request, Object data) {
		super.transformResponse(response, request, data);
		// System.out.println("transformResponse " +
		// JSON.encode(response.getJsObj()));
	}
}
